package com.example.myletcodelearing.one

/**
 * @author tgw
 * @date 2022/11/7
 * @describe https://leetcode.cn/problems/number-of-islands/comments/
 */

fun main(args: Array<String>) {
   var land = Solution7isLand.Solution()

    var grid = arrayOf(
        arrayOf<Char>('1','1','1','1','0'),
        arrayOf<Char>('1','1','0','1','0'),
        arrayOf<Char>('1','1','0','0','0'),
        arrayOf<Char>('0','0','0','0','0'),
    )
    var grid2 = arrayOf(
        arrayOf<Char>('1','1','0','0','0'),
        arrayOf<Char>('1','1','0','0','0'),
        arrayOf<Char>('0','0','1','0','0'),
        arrayOf<Char>('0','0','0','1','1'),
    )

    var num = land.numIslands(grid2)
    print("岛屿数量：$num")
}
private class Solution7isLand {

    internal class Solution {
        fun numIslands(grid: Array<Array<Char>>): Int {
            var islandNum = 0
            for (i in grid.indices) {
                for (j in 0 until grid[0].size) {
                    if (grid[i][j] == '1') {
                        infect(grid, i, j)
                        islandNum++
                    }
                }
            }
            return islandNum
        }

        //感染函数
      private  fun infect(grid: Array<Array<Char>>, i: Int, j: Int) {
            if (i < 0 || i >= grid.size || j < 0 || j >= grid[0].size || grid[i][j] != '1') {
                return
            }
            grid[i][j] = '2'
            infect(grid, i + 1, j)
            infect(grid, i - 1, j)
            infect(grid, i, j + 1)
            infect(grid, i, j - 1)
        }
    }
}